import { ElMessage } from "element-plus";
import { baseURL } from "@/utils/index.js";

function fetch(options = {}) {
  let { url, method = "get", data = {}, params = {} } = options;

  const reqUrl = baseURL + url;

  const optionss = {
    method,
    headers: {
      "Content-Type": "application/json",
    },
  };

  if (method === "get" || method === "delete") {
    optionss.params = params;
  }

  if (method === "post" || method === "put") {
    optionss.body = data;
  }

  return new Promise((resolve, reject) => {
    useFetch(reqUrl, optionss)
      .then(({ data, error }) => {
        if (error.value) {
          reject(error.value);
          return;
        }
        const { value } = data;
        if (!value) {
          ElMessage({
            message: "请求失败，请稍后重试1",
            type: "error",
          });
          return;
        }
        if (value.code != 200) {
          ElMessage({
            message: value.msg || "请求失败，请稍后重试2",
            type: "error",
          });
          return;
        }

        resolve(value);
      })
      .catch((err) => {
        console.log("err", err);
        reject(err);
      });
  });
}

export default fetch;
